import ButtonRegular from "@/components/composite/ButtonRegular/main"
import { useSearchAction } from "@/features/useSearchAction"
import styled from "@emotion/styled"
import { useAtom } from "jotai"
import { Pagination } from "swiper/modules"
import { Swiper, SwiperSlide } from "swiper/react"
import { amountAtom, selectedAmountAtom, selectedPaymentMethodAtom } from "../atom"
import DepositAmount from "../components/DepositAmount"
import Promotions from "../components/Promotions"
// 引入 Swiper 样式
import LazyImage from "@/components/base/LazyImage"
import { SvgComponent } from "@/components/base/Svg"
import { useDepositSubmit, usePaymentMethods } from "@/features/business"
import { useModalSlideUp } from "@/features/useModal"
import { resolveAssetImage } from "@/utils/common"
import { debounce } from "lodash"
import { useEffect } from "react"

const DepositContainer = styled.div`
    position: relative;
    background-color: rgba(242, 243, 245, 1);
    max-height: 95vh;
    height: 620rem;
`

const DepositTitle = styled.div`
    display: flex;
    justify-content: center;
    font-family: "Inter";
    font-weight: 500;
    font-size: 18rem;
    padding-top: 8rem;
    height: 72rem;
    letter-spacing: 0%;
    text-align: center;
    color: rgba(255, 255, 255, 0.95);
    margin-top: -12rem;
    position: relative;
    & > img {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }
    & > span {
        position: relative;
    }
`

const DepositTitleImg = styled.img`
    object-fit: cover;
`

const DepositTitleTxt = styled.span`
    color: rgba(255, 255, 255, 0.95);
    text-align: center;
    text-shadow: 0 2rem 4rem rgba(110, 12, 29, 0.24);
    font-family: Gilroy;
    font-size: 18rem;
    font-style: normal;
    font-weight: 500;
    line-height: 28rem;
`

const PaymentContainer = styled.div`
    padding: 12rem;
    background-color: #ffffff;
    border-radius: 12rem;
    margin-left: 12rem;
    margin-right: 12rem;
`

const PaymentTitle = styled.div`
    font-family: "Gilroy";
    font-weight: 700;
    font-size: 16rem;
    letter-spacing: 0%;
    vertical-align: middle;
    color: #131416;
`

const PaymentMethodsList = styled.div`
    display: flex;
    justify-content: space-between;
    margin-bottom: 8rem;
    margin-top: 12rem;
`
interface isSelected {
    selected: boolean
}
const PaymentMethod = styled.div<isSelected>`
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 8rem;
    border-radius: 6rem;
    outline: ${(props) => (props.selected ? "1rem solid #054BF0" : "none")};
    outline-offset: 0rem;
    color: ${(props) => (props.selected ? "#054BF0" : "#69728C")};
    12rem;
    // font-size: ${(props) => (props.selected ? "16rem" : "12rem")};
`

const PaymentText = styled.div`
    font-family: "Gilroy";
    font-weight: 400;
    letter-spacing: 0%;
    text-align: center;
    vertical-align: middle;
    width: 64rem;
    height: 16rem;
    line-height: 16rem;
    margin-top: 4rem;
`
// 自定义 Swiper 样式
const StyledSwiper = styled(Swiper)`
    .swiper-slide {
        display: flex;
        gap: 1rem;
        /* width: 100%; */
        padding-top: 11rem;
        padding-bottom: 1rem;
        padding-left: 2px;
        padding-right: 2px;
        transition:
            transform 0.5s ease,
            opacity 0.5s ease;
    }

    .swiper-pagination {
        position: relative;
        margin-top: 12rem;
    }

    .swiper-pagination-bullet {
        width: 4rem;
        height: 4rem;
        background: #ddd;
        opacity: 1;
        transition:
            background-color 0.3s ease,
            transform 0.3s ease;
    }

    .swiper-pagination-bullet-active {
        width: 16rem;
        height: 4rem;
        border-radius: 2rem;
        background: #007bff;
        transform: scale(1.2);
    }
`

const BottomBlock = styled.div`
    padding: 12rem;
    background-color: #ffffff;
    position: fixed; /* 固定在底部 */
    bottom: 0;
    width: 100%;
    display: flex;
    justify-content: center;
`

const SubmitButton = styled(ButtonRegular)`
    background: ${({ disabled }) =>
        disabled
            ? "linear-gradient(90deg, #FFADC2 10%, #FFADEB 100%)"
            : "linear-gradient(90deg, #FF3568 10%, #FF33CC 100%)"};
    width: 343rem;
    height: 40rem;
    line-height: 40rem;
    font-weight: 500;
    font-size: 16rem;
    text-align: center;
    color: ${({ disabled }) => (disabled ? "rgba(255, 255, 255, 1)" : "#ffffff")};
    box-shadow: none;
`

const OptionClose = styled(SvgComponent("pages/UserCenterPage/deposit/close.svg"))`
    width: 24rem;
    height: 24rem;
    position: absolute;
    top: 16rem;
    right: 16rem;
`

// 常量
const DEFAULT_MIN_AMOUNT = 100
const DEFAULT_MAX_AMOUNT = 500000
interface RechargeChannel {
    available?: boolean
    category?: string
    displayName?: string
    icon?: string
    limits?: {
        EXCHANGE?: {
            maxAmount?: number
            minAmount?: number
        }
        WEB?: {
            maxAmount?: number
            minAmount?: number
        }
    }
    name?: string
}
export interface RechargeChannelResponse {
    data: RechargeChannel[]
    // 其他响应相关属性...
}
// 支付方式类型
type PaymentMethod = string

// 规范化支付方式名称
const normalizePaymentMethod = (name: string): PaymentMethod => {
    const normalized = name.toLowerCase()
    if (normalized === "lazada_exchange") return "Lazada"
    return normalized
}

export default function Deposit() {
    const [selectedPaymentMethod, setSelectedPaymentMethod] = useAtom<string | null>(
        selectedPaymentMethodAtom,
    )
    const [amount] = useAtom(amountAtom) //输入框金额
    const [selectedAmount] = useAtom(selectedAmountAtom) //选择模块填入的金额

    const handleClose = () => {
        close()
        clearAction()
    }

    const { paymentMethods, channels, loading, error } = usePaymentMethods()
    const { handleWebDeposit, handleLazadaDeposit } = useDepositSubmit({
        onSuccess: handleClose,
    })

    const { close } = useModalSlideUp("search-action")
    const { clearAction } = useSearchAction()

    //默认选中一个支付方式
    useEffect(() => {
        if (!selectedPaymentMethod && paymentMethods.length > 0) {
            setSelectedPaymentMethod(paymentMethods[0])
        }
    }, [selectedPaymentMethod, paymentMethods, setSelectedPaymentMethod])
    // 分组支付方式
    const itemsPerGroup = 4
    const groups = []
    for (let i = 0; i < paymentMethods.length; i += itemsPerGroup) {
        groups.push(paymentMethods.slice(i, i + itemsPerGroup))
    }

    // 选择支付方式
    const handleSelectPaymentMethod = debounce((method: PaymentMethod) => {
        setSelectedPaymentMethod(method)
    })

    // 获取金额限制
    const getAmountLimits = (method: string | null | undefined) => {
        const channel = channels.find((channel) => normalizePaymentMethod(channel.name!) === method)
        const limits = {
            minAmount: channel?.min_amount ? parseFloat(channel?.min_amount) : DEFAULT_MIN_AMOUNT,
            maxAmount: channel?.max_amount ? parseFloat(channel?.max_amount) : DEFAULT_MAX_AMOUNT,
        }
        return limits
    }

    // 验证金额区间
    const validateAmount = () => {
        if (!amount) {
            return false
        }
        const { minAmount, maxAmount } = getAmountLimits(selectedPaymentMethod)
        return (
            parseFloat(amount.toString()) >= minAmount && parseFloat(amount.toString()) <= maxAmount
        )
    }

    const isFormValid = () => {
        return !!selectedPaymentMethod && validateAmount()
    }

    // 提交逻辑
    const handleSubmit = async () => {
        if (!isFormValid()) return new Error("金额错误")
        const finalAmount = selectedAmount || parseFloat(amount?.toString() || "0")
        const channel = channels.find((c) => c.name === selectedPaymentMethod)
        if (!channel) return new Error("未找到充值通道")
        const depositParams = {
            amount: finalAmount,
            pid: channel?.id || "",
            channelName: channel?.name || "",
        }
        if (selectedPaymentMethod === "Lazada") {
            await handleLazadaDeposit(depositParams)
        } else {
            await handleWebDeposit(depositParams)
        }
    }

    const initialSlide = Math.floor(
        paymentMethods.indexOf(selectedPaymentMethod || "") / itemsPerGroup,
    )
    return (
        <DepositContainer>
            <DepositTitle>
                <DepositTitleImg
                    src={resolveAssetImage("pages/UserCenterPage/deposit/deposit_head.webp")}
                    alt=""
                />
                <DepositTitleTxt>Deposit</DepositTitleTxt>
            </DepositTitle>
            <PaymentContainer>
                <PaymentTitle>Payment Methods</PaymentTitle>
                <StyledSwiper
                    modules={[Pagination]}
                    slidesPerView={1}
                    slidesPerGroup={1}
                    spaceBetween={0}
                    pagination={{ clickable: true }}
                    initialSlide={initialSlide}
                    loop={groups.length > 4}
                >
                    {groups.map((group, groupIndex) => (
                        <SwiperSlide key={groupIndex}>
                            {group.map((method) => {
                                const channel = channels.find(
                                    (ch) => normalizePaymentMethod(ch.name!) === method,
                                )
                                return (
                                    <PaymentMethod
                                        key={method}
                                        selected={selectedPaymentMethod === method}
                                        onClick={() => handleSelectPaymentMethod(method)}
                                    >
                                        {/* <PaymentIcon src={channel?.img || ""}></PaymentIcon> */}
                                        <LazyImage
                                            src={channel?.img || ""}
                                            width="36rem"
                                            height="36rem"
                                            styles={{
                                                cover: {
                                                    borderRadius: "4rem",
                                                },
                                            }}
                                        />
                                        <PaymentText>{channel?.name || method}</PaymentText>
                                    </PaymentMethod>
                                )
                            })}
                        </SwiperSlide>
                    ))}
                </StyledSwiper>
            </PaymentContainer>
            <DepositAmount
                min={getAmountLimits(selectedPaymentMethod || "").minAmount}
                max={getAmountLimits(selectedPaymentMethod || "").maxAmount}
            />
            <Promotions />
            <BottomBlock>
                <SubmitButton
                    disabled={!isFormValid()}
                    onClick={handleSubmit}
                >
                    Deposit now
                </SubmitButton>
            </BottomBlock>
            <OptionClose onClick={handleClose}></OptionClose>
        </DepositContainer>
    )
}
